<template>
	<view class="home">
		<view class="form">
			<view class="form-item">
				<view class="label">
					<view class="text">家庭名称</view>
					<view v-if="isOwer" class="btn" @click="handleSetName">
						<text>编辑</text>
						<image :src="$IMAGE_BASE_URL + '/static/ic_edit.png'"></image>
					</view>
				</view>
				<view class="input">{{ homeName }}</view>
			</view>
		</view>
		<view class="member">
			<view class="member-title">家庭成员</view>
			<scroll-view scroll-y class="member-list-wrapper">
				<view class="member-list">
					<u-swipe-action :show="item.show" :index="index" v-for="(item, index) in memberList" :key="index"
						btn-width="130" :options="options" :disabled="isSwipeDisiable(item)" @click="onDeleteMember($event, item)" 
						@content-click="onMember($event, item)" @open="open">
						<view class="member-item">
							<image v-if="item.avatarUrl" class="img" :src="item.avatarUrl"></image>
							<image v-else class="img" src="@/img/new/moren.png"></image>
							<view class="info">
								<view class="name">{{ item.remark || item.nickName || "游客" }}</view>
								<view class="role" v-if="item.role === 'MANAGER'">创建者</view>
							</view>
							<u-icon v-if="item.role != 'MANAGER'" name="arrow-right" size="40" color="#c0c0c0"></u-icon>
						</view>
						<view class="line"></view>
					</u-swipe-action>
					<view class="add-member" @click="toInvite">{{ isOwer ? '添加成员' : '退出家庭' }}</view>
				</view>
			</scroll-view>
		</view>

		<BaseModal :show="isNameShow" type="input" title="家庭名称" :content="homeName" @updateShow="e => isNameShow = e"
			@confirm="onSetNameConfirm" />

		<BaseModal :show="isExitShow" title="退出家庭" :content="exitHomeContent" @updateShow="e => isExitShow = e"
			@confirm="onExitConfirm" />
		
		<BaseModal :show="isDeleteShow" title="删除成员" :content="deleteMemberContent" @updateShow="e => isDeleteShow = e"
			@confirm="onDeleteConfirm" />
		
		<BaseModal :show="isSetShow"  type="input" title="设置备注" :content="nickName" @updateShow="e => isSetShow = e"
			@confirm="onSetConfirm" />

	</view>
</template>

<script>
	import BaseModal from "@/components/base-modal/index.vue";
	import {
		homeMembers
	} from "@/api/login/index.js";
	import {
		updateHome,
		getHomeInfo,
		exitHome,
		setHomeNickName
	} from "@/api/home/index.js";
	import {
		showInfo,
	} from "@/utils/ToastUtils";
	import StorageUtils from "@/utils/StorageUtils";
	import CacheConfig from "@/config/CacheConfig";
	import {
		getCurrentPage
	} from '@/core/app'

	export default {
		data() {
			return {
				homeId: "",
				homeName: "",
				homeUserId: "",
				userId: "",
				memberList: [],
				selectedMember: {},
				nickName: "",
				isNameShow: false,
				isExitShow: false,
				isDeleteShow: false,
				isSetShow: false,

				options: [{
					text: '删除',
					style: {
						backgroundColor: '#dd524d'
					}
				}]
			};
		},
		components: {
			BaseModal
		},
		computed: {
			isOwer() {
				return this.userId == this.homeUserId;
			},
			exitHomeContent() {
				return `是否退出'${this.homeName}'家庭`;
			},
			deleteMemberContent() {
				return `是否删除'${this.selectedMember.remark || this.selectedMember.nickName}'成员`;
			},
		},
		onShow() {
			this.$nextTick(()=>{
				this.homeId = getCurrentPage().query.homeId;
				console.log("homeId", this.homeId);
				this.init();
			})
		},
		methods: {
			async init() {
				try {
					const userInfo = StorageUtils.get(CacheConfig.USER_INFO_KEY);
					this.userId = userInfo.id;
					const homeInfoRes = await getHomeInfo(this.homeId);
					console.log("homeInfo success", homeInfoRes);
					this.homeName = homeInfoRes.obj.homeName;
					this.homeUserId = homeInfoRes.obj.userId;

					const membersRes = await homeMembers({
						homeId: this.homeId
					});
					console.log("membersRes", membersRes);
					const members = [];
					membersRes.obj.forEach((v, i) => {
						let role;
						if (v.id == this.homeUserId) {
							role = "MANAGER";
						} else {
							role = "NORMAL";
						}
						members.push({
							...v,
							role,
							show: false,
						})
					})
					const currentUserIndex = members.findIndex(member => member.id === this.homeUserId);
					if (currentUserIndex !== -1) {
						const currentUser = members.splice(currentUserIndex, 1)[0];
						members.unshift(currentUser);
					}
					console.log("members", members);
					this.memberList = members;
				} catch (err) {
					console.log("init error", err);
					showInfo(err.errMsg);
				}
			},
			isSwipeDisiable(item) {
				const {
					id,
					role
				} = item;
				return !this.isOwer || role == 'MANAGER' || id == this.userId;
			},
			handleSetName() {
				this.isNameShow = true;
			},
			onSetNameConfirm(e) {
				if (!this.$u.trim(e)) {
					showInfo("请输入家庭名称");
					return;
				}
				const param = {
					id: this.homeId,
					homeName: e
				}
				console.log("param", param);
				updateHome(param).then(res => {
					console.log("updateHome success", res);
					this.homeName = e;
					const home = StorageUtils.get("home");
					if(home) {
						home.label = e;
						StorageUtils.save("home", home);
					}
				}).catch(err => {
					console.log("updateHome error", err);
					showInfo(err.errMsg);
				})
			},
			onExitConfirm() {
				this.exit(this.userId).then(res => {
					uni.navigateBack();
				});
			},
			onDeleteConfirm() {
				this.exit(this.selectedMember.id).then(res => {
					const i = this.memberList.findIndex(v => v.id == this.selectedMember.id);
					this.memberList.splice(i, 1);
				});
			},
			onSetConfirm(e) {
				console.log("onSetConfirm", e);
				if (!this.$u.trim(e)) {
					showInfo("请输入备注");
					return;
				}
				const param = {
					nic: e,
					userId: this.userId,
					toUserId: this.selectedMember.id,
				}
				console.log("onSetConfirm param", param);
				setHomeNickName(param).then(res => {
					showInfo("修改成功");
					const i = this.memberList.findIndex(v => v.id == this.selectedMember.id);
					this.memberList[i].remark = e;
				})
			},
			toInvite() {
				if (this.isOwer) {
					uni.navigateTo({
						url: '/pages/mine/invite'
					})
				} else {
					this.isExitShow = true;
				}
			},
			exit(userId) {
				return new Promise((resovle, reject) => {
					const param = {
						homeId: this.homeId,
						userId,
					};
					exitHome(param).then(res => {
						resovle();
					}).catch(err => {
						reject();
					})
				})
			},
			open(index) {
				console.log("openSwipe", index);
				this.memberList[index].show = true;
				this.memberList.map((val, idx) => {
					if (index != idx) this.memberList[idx].show = false;
				})
			},
			onDeleteMember(e, item) {
				console.log("删除", e, item);
				this.selectedMember = JSON.parse(JSON.stringify(item));
				this.isDeleteShow = true;
			},
			onMember(e, item) {
				console.log("onMember", e, item);
				if(this.isSwipeDisiable(item)) return;
				console.log("修改昵称");
				this.selectedMember = item;
				this.nickName = item.remark || item.nickName;
				this.isSetShow = true;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.home {
		height: 100vh;
		background-color: #f5f5f7;
		padding: 0 27rpx;
		box-sizing: border-box;

		.form {
			display: flex;
			flex-direction: column;
			align-items: center;

			.form-item {
				padding-top: 37rpx;

				.label {
					display: flex;
					justify-content: space-between;
					align-items: flex-end;
					margin-bottom: 25rpx;

					.text {
						font-family: SourceHanSansCN;
						font-size: 36rpx;
						font-weight: bold;
						color: #2b2a2e;
						margin-left: 22rpx;
					}

					.btn {
						width: 183rpx;
						height: 64rpx;
						border-radius: 64rpx;
						background-color: #FFFFFF;
						display: flex;
						align-items: center;
						justify-content: center;
						box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.1);

						text {
							font-family: SourceHanSansCN;
							font-size: 30rpx;
							font-weight: bold;
							color: #1d1a1a;
							margin-right: 17rpx;
							margin-top: -5rpx;
						}

						image {
							width: 30rpx;
							height: 30rpx;
						}
					}
				}

				.input {
					width: 700rpx;
					height: 122rpx;
					background: #FFFFFF;
					border-radius: 20rpx;
					box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.1);
					color: #626262;
					font-size: 36rpx;
					display: flex;
					align-items: center;
					padding: 0 30rpx;
					box-sizing: border-box;
					font-weight: bold;
				}

			}
		}

		.member {
			margin-top: 68rpx;

			.member-title {
				font-family: SourceHanSansCN;
				font-size: 36rpx;
				font-weight: bold;
				color: #2b2a2e;
				margin-left: 22rpx;
				margin-bottom: 25rpx;
			}
			
			.member-list-wrapper {
				width: 700rpx;
				height: 970rpx;
				background-color: #ffffff;
				border-radius: 20rpx;
				box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.1);
			}

			.member-list {
				padding: 0 43rpx;
				box-sizing: border-box;

				.member-item {
					height: 172rpx;
					display: flex;
					align-items: center;

					.img {
						width: 89rpx;
						height: 89rpx;
						border-radius: 89rpx;
						margin-right: 20rpx;
					}

					.info {
						flex: 1;
						display: flex;
						flex-direction: column;

						.name {
							font-family: SourceHanSansCN;
							font-size: 36rpx;
							font-weight: bold;
							color: #2b2a2e;
							margin-bottom: 11rpx;
						}

						.role {
							width: 90rpx;
							height: 45rpx;
							font-size: 24rpx;
							color: #FFFFFF;
							display: flex;
							align-items: center;
							justify-content: center;
							border-radius: 10rpx;
							background-color: #0dd30c;
						}
					}
				}

				.line {
					width: 100%;
					height: 12rpx;
					border-radius: 12rpx;
					background-color: #f7f7f8;
				}

				.add-member {
					width: 310rpx;
					height: 96rpx;
					font-family: SourceHanSansCN;
					font-size: 36rpx;
					color: #2b2a2e;
					font-weight: bold;
					background-color: #deefde;
					border-radius: 20rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					margin: 82rpx auto 0 auto;
				}

			}
		}
	}
</style>